import { UPLOADS_DIR } from "$lib/utils/paths";
import fs from "fs";
import path from "path";
import mime from "mime-types";

function formatSize(bytes) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}

function formatDate(date) {
  const pad = (n) => String(n).padStart(2, "0");
  return (date.getFullYear() + "/" + pad(date.getMonth() + 1) + "/" + pad(date.getDate()) + " " + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds()));
}

export async function GET({ url }) {
  try {
    const page = parseInt(url.searchParams.get("page") || "1", 10);
    const limit = parseInt(url.searchParams.get("limit") || "10", 10);
    const allFiles = fs
      .readdirSync(UPLOADS_DIR)
      .map((filename) => {
        const filePath = path.join(UPLOADS_DIR, filename);
        const stats = fs.statSync(filePath);
        return { filename, type: mime.lookup(filename) || "unknown", size: formatSize(stats.size), created_at: formatDate(stats.birthtime), url: `/api/files/${filename}` };
      })
      .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    const total = allFiles.length;
    const start = (page - 1) * limit;
    const end = start + limit;
    const files = allFiles.slice(start, end);
    return new Response(JSON.stringify({ total, page, limit, files }), { headers: { "Content-Type": "application/json" } });
  } catch (err) {
    return new Response(JSON.stringify({ error: err.message }), { status: 500 });
  }
}
